<template>
  <div>
    <el-card shadow="always" :style="{ margin: '20px' }">
      <el-form label-width="80px" :inline="true" size="normal">
        <el-form-item size="normal">
          <el-input
            placeholder="用户名"
            v-model="searchKey"
            size="small"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item :style="{ marginLeft: '20px' }" size="normal">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="goSearch()"
            >查询</el-button
          >
          <el-button size="small" type="infor" @click="goSearch('cl')"
            >清空</el-button
          >
        </el-form-item>
      </el-form>
      <el-button type="primary" size="small" @click="openSave">添加</el-button>
      <el-button
        type="danger"
        size="small"
        @click="delMany"
        :disabled="delList.length === 0"
        >批量删除</el-button
      >
      <el-table
        :data="tableitems"
        :style="{ marginTop: '20px' }"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column label="用户名" prop="username"> </el-table-column>
        <el-table-column label="用户昵称" prop="nickName"> </el-table-column>
        <el-table-column label="角色列表" prop="roleName"> </el-table-column>
        <el-table-column label="创建时间" prop="gmtCreate"> </el-table-column>
        <el-table-column label="更新时间" prop="gmtModified"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="info"
                size="mini"
                icon="el-icon-user"
                @click="allotRole(row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="修改用户"
              placement="top"
            >
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="reWriteUser(row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除用户"
              placement="top"
              :style="{ marginLeft: '10px' }"
            >
              <el-popconfirm title="确定要删除吗?" @onConfirm="delOne(row)">
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  slot="reference"
                ></el-button>
              </el-popconfirm>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="parameter.page"
        :page-sizes="[3, 5, 7, 10]"
        :page-size.sync="parameter.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
      <!-- 新增的dialog -->

      <el-dialog
        :title="title"
        top="0"
        width="80%"
        :visible.sync="dialogFormVisible"
      >
        <el-form
          :model="saveItemFrom"
          :rules="saveItemFromRules"
          label-width="80px"
          :inline="false"
          size="normal"
        >
          <el-form-item label="用户名" size="normal" prop="username">
            <el-input
              size="normal"
              v-model="saveItemFrom.username"
              :disabled="showIndex === 2"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" size="normal" v-show="showIndex !== 2">
            <el-input
              size="normal"
              v-model="saveItemFrom.nickName"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用户密码"
            size="normal"
            prop="password"
            v-show="showIndex === 0"
          >
            <el-input
              size="normal"
              v-model="saveItemFrom.password"
              clearable
              show-password
            ></el-input>
          </el-form-item>
          <!-- // 多选框组 -->

          <el-form-item label="角色列表" size="normal" v-show="showIndex === 2">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
              >全选</el-checkbox
            >
            <el-checkbox-group v-model="checkList">
              <el-checkbox
                :label="item.id"
                v-for="item in userRoleList.allRolesList"
                :value="item.id"
                :key="item.id"
                >{{ item.roleName }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  reqaclUser,
  saveUserInfo,
  requserRole,
  AssignRole,
  reWriteUserinfo,
  deluserItem,
  deluserList
} from "@/api/acl_user";
export default {
  name: "User",
  data() {
    return {
      parameter: {
        page: 1,
        limit: 3
      },
      total: 0,
      tableitems: [],
      loading: false,
      //搜索的关键字
      searchKey: "",
      //dialog的控制
      //对展示内容的控制
      showIndex: 0,
      title: "",
      dialogFormVisible: false,
      saveItemFrom: {
        nickName: "",
        password: "",
        username: ""
      },
      //表单校验条件
      saveItemFromRules: {
        username: [
          { required: true, message: "必须输入用户名", trigger: "blur" },
          { min: 5, max: 7, message: "长度在 5 到 7 个字符", trigger: "blur" }
        ],
        password: [{ required: true, message: "必须输入密码", trigger: "blur" }]
      },
      // 多选框组
      roleList: [],
      // 选中的多选框
      checkList: [],
      // 当前用户的角色
      userRoleList: {},
      // 当前用户的id
      userId: "",
      //多选删除的id列表
      delList: []
    };
  },
  mounted() {
    this.getaclUser();
  },
  methods: {
    async getaclUser(keyWord) {
      let re = await reqaclUser(
        this.parameter.page,
        this.parameter.limit,
        keyWord
      );
      this.total = re.total;
      this.tableitems = re.items;
      this.loading = false;
    },
    async getuserRole(id) {
      let re = await requserRole(id);
      this.userRoleList = re;
      const { allRolesList, assignRoles } = re;
      this.roleList = allRolesList.map(item => item.id);
      this.checkList = assignRoles.map(item => item.id);
    },

    goSearch(ifcl) {
      this.loading = true;
      if (ifcl) {
        this.getaclUser();
      } else {
        this.getaclUser(this.searchKey);
      }
    },
    //打开添加dialog
    openSave() {
      this.saveItemFrom = {
        roleName: "",
        password: "",
        username: ""
      };
      this.title = "添加用户";
      this.showIndex = 0;
      this.dialogFormVisible = true;
    },
    async save() {
      // 根据不同的展开发送不同的请求
      const index = this.showIndex;
      if (index === 0) {
        await saveUserInfo(this.saveItemFrom);
      } else if (index === 1) {
        // 修改用户信息
        const { username, nickName } = this.saveItemFrom;
        await reWriteUserinfo({ username, nickName, id: this.userId });
      } else if (index === 2) {
        await AssignRole(this.userId, this.checkList.join(","));
      }
      this.$message({
        type: "success",
        message: "数据修改成功"
      });
      this.dialogFormVisible = false;
      this.getaclUser();
    },
    handleCheckAllChange(v) {
      //   console.log(v);
      // @change也有获取当前值的参数
    },
    // 分配角色
    allotRole(row) {
      this.showIndex = 2;
      this.title = "设置角色";
      this.dialogFormVisible = true;
      this.saveItemFrom.username = row.username;
      this.userId = row.id;
      this.getuserRole(row.id);
    },
    // 重写user数据
    reWriteUser(row) {
      this.showIndex = 1;
      this.dialogFormVisible = true;
      this.saveItemFrom.username = row.username;
      this.saveItemFrom.nickName = row.nickName;
      this.userId = row.id;
    },
    //单个删除
    async delOne(row) {
      await deluserItem(row.id);
      this.$message({
        type: "success",
        message: "数据删除成功"
      });
      this.getaclUser();
    },
    // 多选回调函数
    handleSelectionChange(file) {
      this.delList = file.map(item => item.id);
    },
    async delMany() {
      this.$confirm("是否删除多个数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await deluserList(this.delList);
        this.$message({
          type: "success",
          message: "数据删除成功"
        });
        this.getaclUser();
      });
    }
  },
  watch: {
    parameter: {
      deep: true,
      handler() {
        this.loading = true;
        this.getaclUser();
      }
    }
  },
  computed: {
    isIndeterminate() {
      const checkListLength = this.checkList.length;
      const roleListLength = this.roleList.length;
      return roleListLength !== checkListLength && checkListLength !== 0;
    },
    checkAll: {
      set(nV) {
        this.checkList = nV ? this.roleList : [];
      },
      get() {
        const checkListLength = this.checkList.length;
        const roleListLength = this.roleList.length;
        return roleListLength === checkListLength;
      }
    }
  }
};
</script>

<style></style>
